package cn.sykj.car.utils;

import org.apache.commons.beanutils.PropertyUtilsBean;
import org.apache.commons.lang3.RandomStringUtils;
import org.apache.commons.lang3.math.NumberUtils;

import javax.servlet.http.HttpServletRequest;
import java.beans.PropertyDescriptor;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * 实用工具类
 */
public class Utils {

    /**
     * 是否为空
     *
     * @return
     */
    public static boolean isEmpty(Object obj) {
        if (obj == null) {
            return true;
        } else if (obj instanceof String) {
            String instance = (String) obj;
            if (instance.trim().length() <= 0) {
                return true;
            }
        } else if (obj instanceof Integer) {
//            Integer instance = (Integer) obj;
//            if (instance < 0) {
//                return true;
//            }
        } else if (obj instanceof List<?>) {
            List<?> instance = (List<?>) obj;
            if (instance.size() <= 0) {
                return true;
            }
        } else if (obj instanceof Map<?, ?>) {
            Map<?, ?> instance = (Map<?, ?>) obj;
            if (instance.size() <= 0) {
                return true;
            }
        } else if (obj instanceof Object[]) {
            Object[] instance = (Object[]) obj;
            if (instance.length <= 0) {
                return true;
            }
        } else if (obj instanceof Long) {
//            Long instance = (Long) obj;
//            if (instance < 0) {
//                return true;
//            }
        }
        return false;
    }

    public static boolean notEmpty(Object obj) {
        return !isEmpty(obj);
    }

    public static void main(String[] args) {

        System.out.println(getRandomNumber());
    }

    /**
     * 获取指定日期当月的第一天
     *
     * @param dateStr
     * @param format
     * @return
     */
    public static String getFirstDayOfGivenMonth(String dateStr, String format) {
        SimpleDateFormat sdf = new SimpleDateFormat(format);
        try {
            Date date = sdf.parse(dateStr);
            Calendar calendar = Calendar.getInstance();
            calendar.setTime(date);
            calendar.set(Calendar.DAY_OF_MONTH, 1);
            calendar.add(Calendar.MONTH, 0);
            return sdf.format(calendar.getTime());
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 获取指定日期下个月的第一天
     *
     * @param dateStr
     * @param format
     * @return
     */
    public static String getFirstDayOfNextMonth(String dateStr, String format) {
        SimpleDateFormat sdf = new SimpleDateFormat(format);
        try {
            Date date = sdf.parse(dateStr);
            Calendar calendar = Calendar.getInstance();
            calendar.setTime(date);
            calendar.set(Calendar.DAY_OF_MONTH, 1);
            calendar.add(Calendar.MONTH, 1);
            return sdf.format(calendar.getTime());
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return null;
    }


    ///list去重
    public static List removeDuplicate(List list) {
        for (int i = 0; i < list.size() - 1; i++) {
            for (int j = list.size() - 1; j > i; j--) {
                if (list.get(j).equals(list.get(i))) {
                    list.remove(j);
                }
            }
        }
        return list;
    }

    /**
     * @param mobileStr
     * @return create by : yuhao
     * description: 验证是否手机号
     * create time:11:22 2018/10/25
     */
    public static boolean isMobile(String mobileStr) {
        if (!Utils.isEmpty(mobileStr) && !mobileStr.matches("^1[34578][0-9]{9}$")) {
            return false;
        }
        return true;
    }


    /**
     * @param obj
     * @return create by : yuhao
     * description: 实体类转换成map
     * create time:21:41 2018/10/26
     */
    public static Map<String, Object> beanToMap(Object obj) {
        Map<String, Object> params = new HashMap<>(0);
        try {
            PropertyUtilsBean propertyUtilsBean = new PropertyUtilsBean();
            PropertyDescriptor[] descriptors = propertyUtilsBean.getPropertyDescriptors(obj);
            for (int i = 0; i < descriptors.length; i++) {
                String name = descriptors[i].getName();
                if (!"class".equals(name)) {
                    params.put(name, propertyUtilsBean.getNestedProperty(obj, name));
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return params;
    }
    

    /**
     * @param date
     * @return create by : libaisheng
     * description: 实体类转换成map
     * create time:21:41 2018/11/19
     * @throws ParseException 
     */
    public static Date getHourMinuteSecond(Date date) throws ParseException {	
    	Calendar now = Calendar.getInstance();
    	
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
		SimpleDateFormat sdf2 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		String dateStr= sdf.format(date);
		dateStr=dateStr+" "+now.get(Calendar.HOUR_OF_DAY)+":"+now.get(Calendar.MINUTE)+":"+now.get(Calendar.SECOND);
		Date today = sdf2.parse(dateStr);
		System.out.println("字符串转成日期：" + today);

      return today;
    }
    public static String getRandomNumber(){
        long time = System.currentTimeMillis();
        String str = String.valueOf(time).concat(RandomStringUtils.random(6,false,true));
        return str;
    }


    public static String getIPAddress(HttpServletRequest request) {
        String ip = null;

        //X-Forwarded-For：Squid 服务代理
        String ipAddresses = request.getHeader("X-Forwarded-For");

        if (ipAddresses == null || ipAddresses.length() == 0 || "unknown".equalsIgnoreCase(ipAddresses)) {
            //Proxy-Client-IP：apache 服务代理
            ipAddresses = request.getHeader("Proxy-Client-IP");
        }

        if (ipAddresses == null || ipAddresses.length() == 0 || "unknown".equalsIgnoreCase(ipAddresses)) {
            //WL-Proxy-Client-IP：weblogic 服务代理
            ipAddresses = request.getHeader("WL-Proxy-Client-IP");
        }

        if (ipAddresses == null || ipAddresses.length() == 0 || "unknown".equalsIgnoreCase(ipAddresses)) {
            //HTTP_CLIENT_IP：有些代理服务器
            ipAddresses = request.getHeader("HTTP_CLIENT_IP");
        }

        if (ipAddresses == null || ipAddresses.length() == 0 || "unknown".equalsIgnoreCase(ipAddresses)) {
            //X-Real-IP：nginx服务代理
            ipAddresses = request.getHeader("X-Real-IP");
        }

        //有些网络通过多层代理，那么获取到的ip就会有多个，一般都是通过逗号（,）分割开来，并且第一个ip为客户端的真实IP
        if (ipAddresses != null && ipAddresses.length() != 0) {
            ip = ipAddresses.split(",")[0];
        }

        //还是不能获取到，最后再通过request.getRemoteAddr();获取
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ipAddresses)) {
            ip = request.getRemoteAddr();
        }
        return ip;
    }

    /**
     * 隐藏银行卡号
     * @param account 卡号
     * @return 隐藏后卡号
     */
    public static String hideBankAccount(String account) {
        String start = account.substring(0, 4);
        String end = account.substring(account.length() - 4);
        String hideAccount = start + " **** **** " + end;
        return hideAccount;
    }

    /**
     * 取银行卡尾号
     * @param account 卡号
     * @return 尾号
     */
    public static String bankAccountLastNumber(String account) {
        String end = account.substring(account.length() - 4);
        return end;
    }

    /**
     * @param orderNo 订单编号
     * @return year
     * 根据订单号取年
     * @throws ParseException
     */
    /**
     * @param orderNo 订单编号
     * @return year
     * 根据订单号取年
     * @throws ParseException
     */
    public static Integer getOrderYear(String orderNo) {
        if (orderNo == null || orderNo.length() < 4) {
            return null;
        }
        String year = "20" + orderNo.substring(2, 4);
        return NumberUtils.createInteger(year);
    }

    /**
     * @param orderNo 订单编号
     * @return year
     * 根据订单号取月
     * @throws ParseException
     */
    public static Integer getOrderMonth(String orderNo) {
        if (orderNo == null || orderNo.length() < 6) {
            return null;
        }
        String year = orderNo.substring(4, 6);
        if (year.startsWith("0")) {
            year = year.substring(1, 2);
        }
        return NumberUtils.createInteger(year);
    }
}
